package com.example.app.ui.health.User.BleTooth;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.RequiresPermission;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import com.example.app.R;
import com.example.app.ui.health.User.HeartRateActivity;

import java.lang.reflect.Method;
import java.util.ArrayList;
public class BleTooth extends AppCompatActivity {
    private static final int REQ_PERMISSION_CODE = 1;
    public BlueToothController btController = new BlueToothController();
    private Toast mToast;
    public ArrayList<String> requestList = new ArrayList<>();
    private IntentFilter foundFilter;
    public ArrayAdapter adapter1;
    public ArrayList<String> arrayList=new ArrayList<>();
    public ArrayList<String> deviceName=new ArrayList<>();
    private final BroadcastReceiver receiver = new BroadcastReceiver(){

        @Override
        public void onReceive(Context context, Intent intent) {
            int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1);
            switch (state){
                case BluetoothAdapter.STATE_OFF:
                    showToast("STATE_OFF");
                    break;
                case BluetoothAdapter.STATE_ON:
                    showToast("STATE_ON");
                    break;
                case BluetoothAdapter.STATE_TURNING_OFF:
                    showToast("STATE_TURNING_OFF");
                    break;
                case BluetoothAdapter.STATE_TURNING_ON:
                    showToast("STATE_TURNING_ON");
                    break;
                default:
                    showToast("UnKnow STATE");
                    unregisterReceiver(this);
                    break;
            }
        }
    };
    private final BroadcastReceiver bluetoothReceiver = new BroadcastReceiver() {
        @RequiresPermission(Manifest.permission.BLUETOOTH_CONNECT)
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                String s;
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                assert device != null;
                if (device.getBondState() == 12) {
                    s = "设备名：" + device.getName() + "\n" + "设备地址：" + device.getAddress() + "\n" + "连接状态：已配对" + "\n";
                }
                else if (device.getBondState() == 10){
                    s = "设备名：" + device.getName() + "\n" + "设备地址：" + device.getAddress() + "\n" + "连接状态：未配对" +"\n";
                }else{
                    s = "设备名：" + device.getName() + "\n" + "设备地址：" + device.getAddress() + "\n" + "连接状态：未知" + "\n";
                }
                if (!deviceName.contains(s)) {
                    deviceName.add(s);
                    arrayList.add(device.getAddress());
                    adapter1.notifyDataSetChanged();
                }
            }else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
                showToast("搜索结束");
                unregisterReceiver(this);
            }else if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)){
                showToast("开始搜索");
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.bletooth);
        IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
        registerReceiver(receiver, filter);
        foundFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        foundFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        foundFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        ListView listView = findViewById(R.id.listview1);
        adapter1 = new ArrayAdapter(this, android.R.layout.simple_expandable_list_item_1, deviceName);
        listView.setAdapter(adapter1);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @RequiresPermission(allOf = {Manifest.permission.BLUETOOTH_CONNECT, Manifest.permission.BLUETOOTH_SCAN})
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                CharSequence content = ((TextView) view).getText();
                String con = content.toString();
                String[] conArray = con.split("\n");
                String rightStr = conArray[1].substring(5, conArray[1].length());
                BluetoothDevice device = btController.find_device(rightStr);
                if (device.getBondState() == BluetoothDevice.BOND_NONE) {
                    btController.cancelSearch();
                    String s = "设备名：" + device.getName() + "\n" + "设备地址：" + device.getAddress() + "\n" + "连接状态：未配对"  + "\n";
                    deviceName.remove(s);
                    device.createBond();
                    s = "设备名：" + device.getName() + "\n" + "设备地址：" + device.getAddress() + "\n" + "连接状态：已配对"  + "\n";
                    deviceName.add(s);
                    adapter1.notifyDataSetChanged();
                    showToast("配对：" + device.getName());
                    registerReceiver(new BroadcastReceiver() {
                        @Override
                        public void onReceive(Context context, Intent intent) {
                            if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(intent.getAction())) {
                                int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR);
                                if (state == BluetoothDevice.BOND_BONDED) {
                                    Intent hrIntent = new Intent(BleTooth.this, HeartRateActivity.class);
                                    hrIntent.putExtra("DEVICE_ADDRESS", device.getAddress());
                                    startActivity(hrIntent);
                                    unregisterReceiver(this); // 注销接收器
                                }
                            }
                        }
                    }, new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED));
                } else if (device.getBondState() == BluetoothDevice.BOND_BONDED) { // 已配对
                    Intent intent = new Intent(BleTooth.this, HeartRateActivity.class);
                    intent.putExtra("DEVICE_ADDRESS", device.getAddress());
                    startActivity(intent);
                } else {
                    showToast("设备状态未知");
                }
            }
        });
        Button button_1 = (Button) findViewById(R.id.button3);
        button_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getPermision();
                boolean ret = btController.isSupportBlueTooth();
                showToast("是否支持蓝牙" + ret);
            }
        });
        Button button_2 = (Button) findViewById(R.id.button4);
        button_2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getPermision();
                boolean ret = btController.getBlueToothStatus();
                showToast("当前蓝牙状态：" + ret);
            }
        });
        Button button_3 = (Button) findViewById(R.id.button7);
        button_3.setOnClickListener(new View.OnClickListener() {
            @RequiresPermission(Manifest.permission.BLUETOOTH_CONNECT)
            @Override
            public void onClick(View view) {
                turnONbt();
            }
        });
        Button button_4 = (Button) findViewById(R.id.button8);
        button_4.setOnClickListener(new View.OnClickListener() {
            @RequiresPermission(Manifest.permission.BLUETOOTH_CONNECT)
            @Override
            public void onClick(View view) {
                getPermision();
                btController.turnOffBlueTooth();
            }
        });
        Button button_5 = (Button) findViewById(R.id.button9);
        button_5.setOnClickListener(new View.OnClickListener() {
            @RequiresPermission(Manifest.permission.BLUETOOTH_ADVERTISE)
            @Override
            public void onClick(View view) {
                BTVisible();
            }
        });
        Button button_6 = findViewById(R.id.button10);
        button_6.setOnClickListener(new View.OnClickListener() {
            @RequiresPermission(Manifest.permission.BLUETOOTH_SCAN)
            @Override
            public void onClick(View view) {
                getPermision();
                registerReceiver(bluetoothReceiver, foundFilter);
                arrayList.clear();
                deviceName.clear();
                adapter1.notifyDataSetChanged();
                btController.findDevice();
            }
        });
        Button button_7 = findViewById(R.id.button11);
        button_7.setOnClickListener(new View.OnClickListener() {
            @RequiresPermission(Manifest.permission.BLUETOOTH_CONNECT)
            @Override
            public void onClick(View view) {
                getPermision();
                deviceName.clear();
                arrayList.clear();
                adapter1.notifyDataSetChanged();
                ArrayList<BluetoothDevice> bluetoothDevices = btController.getBondedDeviceList();
                for (int i = 0; i < bluetoothDevices.size(); i++){
                    BluetoothDevice device = bluetoothDevices.get(i);
                    arrayList.add(device.getAddress());
                    if (device.getBondState() == 12) {
                        deviceName.add("设备名：" + device.getName() + "\n" + "设备地址：" + device.getAddress() + "\n" + "连接状态：已配对" + "\n");
                    }
                    else if (device.getBondState() == 10){
                        deviceName.add("设备名：" + device.getName() + "\n" + "设备地址：" + device.getAddress() + "\n" + "连接状态：未配对" +"\n");
                    }else{
                        deviceName.add("设备名：" + device.getName() + "\n" + "设备地址：" + device.getAddress() + "\n" + "连接状态：未知" + "\n");
                    }
                    adapter1.notifyDataSetChanged();
                }
            }
        });
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK){
            showToast("open successfully");
        }
        else{
            showToast("open unsuccessfully");
        }
    }
    private void unpairDevice(BluetoothDevice device) {
        try {
            Method m = device.getClass()
                    .getMethod("removeBond", (Class[]) null);
            m.invoke(device, (Object[]) null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @RequiresPermission(Manifest.permission.BLUETOOTH_CONNECT)
    public void turnONbt(){
        getPermision();
        btController.turnOnBlueTooth(this,1);
    }
    @RequiresPermission(Manifest.permission.BLUETOOTH_ADVERTISE)
    public void BTVisible(){
        getPermision();
        btController.enableVisibly(this);
    }
    public void getPermision(){
        requestList.add(Manifest.permission.BLUETOOTH_SCAN);
        requestList.add(Manifest.permission.BLUETOOTH_ADVERTISE);
        requestList.add(Manifest.permission.BLUETOOTH_CONNECT);
        requestList.add(Manifest.permission.ACCESS_FINE_LOCATION);
        requestList.add(Manifest.permission.ACCESS_COARSE_LOCATION);
        requestList.add(Manifest.permission.BLUETOOTH);
        ActivityCompat.requestPermissions(this, requestList.toArray(new String[0]), REQ_PERMISSION_CODE);
    }
    public void showToast(String text){
        if( mToast == null){
            mToast = Toast.makeText(this, text, Toast.LENGTH_SHORT);
        }
        else{
            mToast.setText(text);
        }
        mToast.show();
    }
}
